<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { ImageVO, ImageSearchParams, ImageType } from '@/api/Image.ts'
import { ImageApi } from '@/api/ImageApi.ts'
import httpClient from '@/api/client.ts'
import UploadDialog from './components/UploadDialog.vue'
import DeleteDialog from './components/DeleteDialog.vue'
import { ReloadOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', align: 'center' },
  { title: '类型', dataIndex: 'type', key: 'type', align: 'center' },
  { title: '预览', dataIndex: 'preview', key: 'preview', align: 'center' },
  { title: '状态', dataIndex: 'enabled', key: 'enabled', align: 'center' },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime', align: 'center' },
  { title: '操作', dataIndex: 'operation', align: 'center' },
]

const loading = ref(false)
const tableData = ref<ImageVO[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
})

const queryParams = ref<ImageSearchParams>({
  id: null,
  type: null,
  enabled: null,
})

const typeOptions: { label: string; value: ImageType }[] = [
  { label: '轮播图', value: 'CAROUSEL' },
  { label: '验证码', value: 'CAPTCHA' },
]

const enabledOptions = [
  { label: '启用', value: true },
  { label: '禁用', value: false },
]

const toUrl = (path: string) => {
  if (!path) return ''
  if (/^https?:\/\//.test(path)) return path
  const base = (httpClient.defaults?.baseURL || '').replace(/\/$/, '')
  const p = path.startsWith('/') ? path : `/${path}`
  return `${base}${p}`
}

const sanitizeParams = (params: ImageSearchParams) => {
  return {
    id: params.id !== null && String(params.id).trim() !== '' ? String(params.id).trim() : null,
    type: params.type !== null && String(params.type).trim() !== '' ? String(params.type).trim() : null,
    enabled: typeof params.enabled === 'boolean' ? params.enabled : null,
  }
}

const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      ...sanitizeParams(queryParams.value),
      pageNumber: pagination.current,
      pageSize: pagination.pageSize,
    }
    const data = await ImageApi.search(params)
    tableData.value = data?.records || []
    pagination.current = data?.pageNumber || 1
    pagination.pageSize = data?.pageSize || 10
    pagination.total = data?.totalRow || 0
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})

const onSearch = () => {
  pagination.current = 1
  fetchData()
}

const onReset = () => {
  queryParams.value = { id: null, type: null, enabled: null }
  pagination.current = 1
  fetchData()
}

const handleTableChange = (pag: any) => {
  pagination.current = pag?.current || 1
  pagination.pageSize = pag?.pageSize || 10
  fetchData()
}

const uploadOpen = ref(false)
const onUploadOpenChange = (open: boolean) => {
  uploadOpen.value = open
}
const onUploadSuccess = () => {
  message.success('上传成功')
  uploadOpen.value = false
  fetchData()
}

const deleteDialogOpen = ref(false)
const deletingId = ref<string | null>(null)
const onDelete = (id: string) => {
  deletingId.value = id
  deleteDialogOpen.value = true
}
const onDeleteDialogOpenChange = (open: boolean) => {
  deleteDialogOpen.value = open
  if (!open) {
    deletingId.value = null
  }
}
const onDeleteSuccess = () => {
  deleteDialogOpen.value = false
  deletingId.value = null
  fetchData()
}

const onEnable = async (id: string) => {
  const ok = await ImageApi.enable(id)
  if (ok) {
    message.success('已启用')
    fetchData()
  }
}

const onDisable = async (id: string) => {
  const ok = await ImageApi.disable(id)
  if (ok) {
    message.success('已禁用')
    fetchData()
  }
}
</script>

<template>
  <div class="w-full">
    <a-card
      title="图片管理"
      class="w-full rounded-lg shadow-sm"
      :bodyStyle="{ padding: '24px' }"
    >
      <div class="mb-6 flex flex-wrap items-center gap-4">
        <div class="flex items-center gap-2">
          <label class="text-sm font-medium text-gray-700 whitespace-nowrap">ID:</label>
          <a-input
            v-model:value="queryParams.id"
            placeholder="输入ID"
            allow-clear
            @pressEnter="onSearch"
            class="w-[200px]"
          />
        </div>

        <div class="flex items-center gap-2">
          <label class="text-sm font-medium text-gray-700 whitespace-nowrap">类型:</label>
          <a-select
            v-model:value="queryParams.type"
            placeholder="选择类型"
            allow-clear
            class="w-[200px]"
          >
            <a-select-option v-for="opt in typeOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</a-select-option>
          </a-select>
        </div>

        <div class="flex items-center gap-2">
          <label class="text-sm font-medium text-gray-700 whitespace-nowrap">状态:</label>
          <a-select
            v-model:value="queryParams.enabled"
            placeholder="选择状态"
            allow-clear
            class="w-[160px]"
          >
            <a-select-option v-for="opt in enabledOptions" :key="String(opt.value)" :value="opt.value">
              {{ opt.label }}
            </a-select-option>
          </a-select>
        </div>

        <div class="flex items-center gap-2 ml-auto">
          <a-button type="primary" @click="onSearch" class="px-6">
            搜索
          </a-button>
          <a-tooltip title="重置">
            <a-button
              @click="onReset"
              :shape="'default'"
              class="w-9 h-9 p-0 flex items-center justify-center"
            >
              <template #icon>
                <ReloadOutlined />
              </template>
            </a-button>
          </a-tooltip>
          <a-button type="dashed" @click="uploadOpen = true">
            <template #icon>
              <PlusOutlined />
            </template>
            上传图片
          </a-button>
        </div>
      </div>

      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        rowKey="id"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showTotal: (total: number) => `共 ${total} 条`
        }"
        @change="handleTableChange"
        :scroll="{ x: 1200 }"
        class="rounded-lg"
        :customRow="(record: any) => ({ class: 'hover:bg-slate-50' })"
        :customHeaderRow="() => ({ class: 'bg-slate-50 border-b-2 border-slate-200' })"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'preview'">
            <a-image :width="64" :src="toUrl(record.path)" />
          </template>
          <template v-else-if="column.key === 'enabled'">
            <a-tag :color="record.enabled ? 'green' : 'red'">
              {{ record.enabled ? '启用' : '禁用' }}
            </a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'operation'">
            <a-space>
              <a-button type="link" size="small" @click="record.enabled ? onDisable(record.id) : onEnable(record.id)">
                {{ record.enabled ? '禁用' : '启用' }}
              </a-button>
              <a-button type="link" size="small" danger @click="onDelete(record.id)">删除</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>

  <upload-dialog :open="uploadOpen" @update:open="onUploadOpenChange" @success="onUploadSuccess" />
  <delete-dialog
    :open="deleteDialogOpen"
    :id="deletingId"
    @update:open="onDeleteDialogOpenChange"
    @success="onDeleteSuccess"
  />
</template>


